import { useEffect, useRef } from "react";
import { useOutlet, useLocation } from "react-router-dom"

interface KeepAliveProps {
  /** 需要缓存路由数组 */
  includes: string[],
  /** 不需要缓存路由数组 */
  excludes?: string[]
}

const KeepAlive: React.FC<KeepAliveProps> = ({
  includes = [],
  excludes = []
}) => {
  const outlet = useOutlet();
  const { pathname } = useLocation();
  const cmptList = useRef(new Map());

  useEffect(() => {
    init()
  }, [pathname, includes])

  function init() {
    cmptList.current.forEach((__, key) => {
      if (!includes.includes(key)) {
        cmptList.current.delete(key);
      }
    })
    
    if (!cmptList.current.get(pathname)) {
      
    }
    cmptList.current.set(pathname, outlet);
  }

  /** 获取缓存列表 */
  function getCecheList() {
    return includes.filter(item => !excludes.includes(item));
  }

  function render() {
    const ceches = getCecheList();
    console.log('lllll', cmptList.current, pathname, ceches)
    if (ceches.includes(pathname)) {
      return cmptList.current.get(pathname);
    }
    return outlet;
  }

  return render()
}

export default KeepAlive